package com.basker.pisces.logger;

import java.io.File;
import java.net.URL;
import java.util.function.Consumer;

import org.slf4j.LoggerFactory;

import com.basker.pisces.exception.ExceptionFactory;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.util.StatusPrinter;

/**
 * 手动加载logback的配置文件
 *
 * @author hangwen
 */
public class LogBackXmlConfigLoader {
    public static void load(File file) {
        load0(c -> {
            try {
                c.doConfigure(file);
            } catch (JoranException e) {
                throwJoranExceptionRuntimeException(file, e);
            }
        });
    }

    public static void load(URL url) {
        load0(c -> {
            try {
                c.doConfigure(url);
            } catch (JoranException e) {
                throwJoranExceptionRuntimeException(url, e);
            }
        });
    }

    private static void load0(Consumer<JoranConfigurator> consumer) {
        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();

        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(lc);

        consumer.accept(configurator);

        StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
    }

    private static void throwJoranExceptionRuntimeException(Object source, JoranException e) {
        throw ExceptionFactory.createRuntimeException(e, "pisces-logger.LogBackConfigLoader.load-001",
                source.toString(), e.getMessage());
    }
}
